package algorithm.easy;

import java.util.Arrays;

public class Solution66 {

    //输入：digits = [1,2,3]
    //输出：[1,2,4]
    //解释：输入数组表示数字 123。
    public static int[] plusOne(int[] digits) {
        //申请比digits多一位的数组，防止数据溢出
        int[] res = new int[digits.length+1];
        int i = res.length-1;
        int carrayFlag = 1;
        while(i>0){
           if(digits[i-1]==9 &&carrayFlag==1){
               carrayFlag = 1;
               res[i] = 0;
           }else{
               res[i] = digits[i-1]+carrayFlag ;
               carrayFlag = 0;
           }
           i--;
        }
        if(carrayFlag==1){
            res[0] = 1;
        }else{
            int[] rest = new int[digits.length];
            System.arraycopy(res,1,rest,0,digits.length);
            res = rest;
        }
        return res;
        /*
         int[] carray = new int[digits.length+1];
        for(int i=digits.length-1;i>=0;i--){
            if(digits[i]==9){
                carray[i+1] = 1;
            }else{
                if(i==digits.length-1){
                    digits[i] +=1;
                }
            }
            if(digits[i]==9 && carray[i+1]==1){
                carray[i] = 1;
                digits[i] = 0 ;
            }else{
                digits[i] = digits[i]+carray[i+1] ;
            }
        }
        if(carray[0] ==1){
            System.arraycopy(digits,0,carray,1,digits.length);
            return carray;
        }else{
            return digits;
        }*/

    }

    public static void main(String[] args){
        int[] digits = {1,0,0,8,9};
        System.out.print(Arrays.toString(plusOne(digits)));
    }


}
